/** ###################################################################
**     Filename  : SpdIn.C
**     Project   : Motologger_v2
**     Processor : MC9S12XD256BMFU
**     Compiler  : CodeWarrior HCS12X C Compiler
**     Date/Time : 11/15/2009, 2:47 PM
**     Contents  :
**         User source code
**
**     (c) Copyright UNIS, spol. s r.o. 1997-2007
**     UNIS, spol. s r.o.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/

/* MODULE SpdIn */

//is this a single gate on the wheel? if so then:
//(guestimated based on tire sizing suggesting 18" diameter --
//if this doesn't include tire size, could be more like 24)
//at 1mph, expect a pulse every 3 seconds
//at 120mph about 37 pulses a second

//#include "SpdIn_PA.h"
//#include "SpdCounter.h"
#include "Cpu.h"
unsigned short SpdIn_tcnt_prev;
unsigned long SpdIn_dt;
unsigned long SpdIn_idt;

/*
//original
unsigned short SpdIn_GetVal(void){
  if(0==SpdIn_dt)
  	return 0;
  return 4261363ul/SpdIn_dt;
  
}
*/


 //correct 1
short spdAbs(unsigned short a, unsigned short b){
  short sa, sb;
  sa = (short) a;
  sb = (short) b;
  if( (sa-sb) < 0 ) return sb-sa;
  else return sa-sb;	
}

unsigned short spdVal=0;
unsigned short pSpdVal=0;
unsigned short SpdIn_GetVal(void){
  pSpdVal = spdVal;
  if(0==SpdIn_dt)
  	spdVal = 0;
  else 
    spdVal = 2536640ul/SpdIn_dt; //calibration
  
  if( spdAbs(spdVal,pSpdVal) < 10 ) return spdVal;
  else return spdVal>pSpdVal ? pSpdVal : spdVal; 
  
}
 


#define SPD_TIMESLICE 8 //ModCounter is running TIMESLICE x faster than 1mph per latch

void SpdIn_Periodic_Reset(void){//scheduled event
/*	static unsigned char counter;
	static unsigned short speedCounts;
	DbgOut_NegBit(5);
	counter = (counter+1)%SPD_TIMESLICE;
	if(!counter){
		spd_val = speedCounts;
		speedCounts = SpdIn_PA_GetHoldValue();
	}else{
		speedCounts += SpdIn_PA_GetHoldValue();
	} */
	SpdIn_idt+=TCNT-SpdIn_tcnt_prev;
	SpdIn_tcnt_prev=TCNT;
	if(SpdIn_idt>4260000ul)
		SpdIn_dt=0;	
	
}


bool SpdResetFlag;

void SpdSetFlag(void){
	SpdResetFlag = 1;
}

void SpdIn_Update(void){
/*	static unsigned long timeSum;
	static unsigned char timeCount;
	
	if(SpdResetFlag){ 
		spd_val = timeSum/timeCount;
		timeSum = 0;		
		SpdResetFlag = 0;
	}else{
		timeSum += SpeedTimer_GetCaptureValue();
		timeCount++;
	}	*/
	
	SpdIn_idt+=TCNT-SpdIn_tcnt_prev;
	SpdIn_tcnt_prev=TCNT;
	SpdIn_dt=SpdIn_idt;
	SpdIn_idt=0;
	
								
}

void SpdIn_Init(void){
 // static word period = 212;
 // SpdCounter_SetPeriodMS(period); //calculate this value based on wheel size
 SpdIn_dt=0;
 SpdIn_idt=0;
 SpdIn_tcnt_prev=TCNT; 
}

/* END SpdIn */
